/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.questionnaire.questionnaire;

import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.questionnaire.FillQuestionnaireForm;
import com.blandware.atleap.webapp.util.questionnaire.QuestionnaireModuleWebConstants;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.service.questionnaire.QuestionnaireManager;
import com.blandware.atleap.common.QuestionnaireModuleConstants;
import com.blandware.atleap.model.questionnaire.Questionnaire;
import com.blandware.atleap.model.questionnaire.Question;
import com.blandware.atleap.model.questionnaire.AnswerOption;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;

/**
 * <p>Shows a page with questionnaire to fill.</p>
 * <p><a href="CallFillQuastionnaireAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.4 $ $Date: 2006/06/16 10:25:42 $
 * @struts.action name="fillQuestionnaireForm"
 * path="/questionnaire/questionnaire/callFill"
 * validate="false"
 * @struts.action-forward name="fillQuestionnaire"
 * path=".questionnaire.questionnaire.fill"
 * @struts.action-forward name="listQuestionnairesToFill"
 * path="/questionnaire/questionnaire/listToFill.do"
 * redirect="true"
 */
public final class CallFillQuastionnaireAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request,
                                 HttpServletResponse response)
            throws IOException {
        HttpSession session = request.getSession();
        session.removeAttribute(QuestionnaireModuleWebConstants.FILL_QUESTIONNAIRE_SUBMITTED_ACTION_KEY);

        FillQuestionnaireForm fillQuestionnaireForm = (FillQuestionnaireForm) form;
        Long questionnaireId = null;
        if (fillQuestionnaireForm.getId() != null) {
            questionnaireId = fillQuestionnaireForm.getId();
        }
        if (questionnaireId == null) {
            if (log.isInfoEnabled()) {
                log.info("Missing questionnaire ID, returning to list...");
                return mapping.findForward("listQuestionnairesToFill");
            }
        }

        QuestionnaireManager questionnaireManager = (QuestionnaireManager) getBean(QuestionnaireModuleConstants.QUESTIONNAIRE_MANAGER_BEAN);
        Questionnaire questionnaire = questionnaireManager.retrieveQuestionnaire(questionnaireId);
        if (questionnaire == null) {
			// questionnaire not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("questionnaireNotFound", new ActionMessage("questionnaire.questionnaire.errors.notFound"));
			saveErrors(request, errors);
            return mapping.findForward("listQuestionnairesToFill");
        }

        if (!questionnaire.getActive().booleanValue()) {
			response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
			return null;
        }

        // selecting some values for required multi-option fields
        List questions = new ArrayList(questionnaire.getQuestions());
        for (Iterator i = questions.iterator(); i.hasNext(); ) {
            Question question = (Question) i.next();
            if (question.getRequired().booleanValue()) {
                switch (question.getType()) {
                case Question.DROPDOWN_LIST:
                    // fall through
                case Question.RADIO_BUTTONS:
                    if (question.getAnswerOptions().size() > 0) {
                        AnswerOption firstOption = (AnswerOption) question.getAnswerOptions().get(0);
                        String id = question.getId().toString();
                        Long optionId = firstOption.getId();
                        fillQuestionnaireForm.setIntQuestion(id, optionId);
                    }
                    break;
                }
            }
        }

        request.setAttribute(WebappConstants.DISPLAYED_OBJECT_URI_KEY,
                             questionnaire.getUri());

        request.setAttribute("questionnaire", questionnaire);

        return mapping.findForward("fillQuestionnaire");
    }
}
